let globalData; // 定义全局变量
let displayedJobs = 6; // 初始显示5个职位

async function fetchData() {
    try {
        const response = await fetch('http://localhost:3000/companys/list?page=2&pageSize=20', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'token':sessionStorage.getItem('token') // 确保token值被正确设置
            }
        });
        if (response.ok) {
            globalData = await response.json(); // 将数据赋给全局变量
            console.log(globalData); // 输出获取到的数据
            return globalData;
        } else {
            console.error('无效的token');
        }
    } catch (error) {
        console.error(error);
    }
}

document.addEventListener('DOMContentLoaded', async function() {
    await fetchData(); // 获取数据
    if (globalData) {
        displayData({ rows: globalData.rows, total: globalData.total });
    }
});

// 将数据显示到页面上
function displayData(data) {
    const dataContainer = document.getElementById('dataContainer');
    dataContainer.innerHTML = '';

    data.rows.slice(0, displayedJobs).forEach(item => {
        const itemDiv = document.createElement('li');
        itemDiv.innerHTML = `
        <div class="sub-li">
        <div class="company_img">
             <img src="${item.img}" alt="">
    </div>
        <div class="company_info">
            <h3>${item.company}</h3>
            <p class="job-text">
            <span>${item.address}</span></p>
            <p>${item.industry_type}</p>
        </div>

    </div>
        `;

        itemDiv.addEventListener('click', () => showJobDetails(item));

        dataContainer.appendChild(itemDiv);
    });

    if (displayedJobs < data.rows.length) {
        const moreButton = document.createElement('button');
        moreButton.textContent = '查看更多';
        moreButton.addEventListener('click', showMoreJobs);
        dataContainer.appendChild(moreButton);
    }
}

function showJobDetails(job) {
    alert(`公司详情:\n 公司名称: ${job.company}\n工作地点: ${job.address}\n行业类型: ${job.industry_type}\n公司类型: ${job.type}\n联系方式: ${job.telephone}`);
}

// 搜索职位
async function searchJob() {
    const keyword = document.getElementById('searchInput').value;
    const data = await fetchData(); // 获取数据
    if (data) {
        const filteredData = data.rows.filter(item => item.company.includes(keyword));
        displayedJobs = 15; // 重置显示的职位数量
        displayData({ rows: filteredData, total: data.total });
    }
}

// 显示更多职位
function showMoreJobs() {
    displayedJobs += 6; // 每次点击增加5个职位
    displayData({ rows: globalData.rows, total: globalData.total });
}
//分类
function showCompaniesByRegion(region) {
    const filteredData = globalData.rows.filter(item => item.type.includes(region));
    displayedJobs = 9; 
    displayData({ rows: filteredData, total: globalData.total });
}

// 初始化页面时显示原始数据
fetchData();